<?php

namespace core\middleware\element;

use core\lib\tool\Token;
use Exception;
use Webman\MiddlewareInterface;
use Webman\Http\Request;
use Webman\Http\Response;

use app\bll\AdminMenu as BllAdminMenu;
use app\bll\SiteAdmin as bllSiteAdmin;
use app\bll\SiteRole as BllSiteRole;


class AuthIntercept implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {

        if (is_element()) {

            $element_token = request()->get('token', '');
            if (!$element_token) {
                throw new Exception('非法提交');
            }

            try {
                //验证Token
                $tokenArr = Token::verifyToken($element_token);

                if (
                    strncmp($tokenArr['data']->controller, 'uc/', 3) === 0
                    &&
                    request()->session()->get('userinfo') == null
                ) {
                    throw new Exception('无权限');
                }


                if (
                    strncmp($tokenArr['data']->controller, 'admin/', 5) === 0
                    &&
                    request()->session()->get('admininfo') == null
                ) {
                    throw new Exception('无权限');
                }


                //判断是否是后台
                if (
                    strncmp($tokenArr['data']->controller, 'admin/', 5) === 0
                    && request()->session()->get('admininfo')['issystem'] != 1
                ) {
                    $admininfo = request()->session()->get('admininfo');
                    //非系统超级管理员 需要验证权限
                    $bllAdminMenu = new BllAdminMenu();
                    $nowmenu   = $bllAdminMenu->findByUrl($tokenArr['data']->url);
                    if ($nowmenu['belong'] == 2) {
                        // 若当前菜单属于站点管理员无权限的类型，抛出异常
                        throw new Exception('没有权限');
                    }

                    $bllSiteAdmin  = new bllSiteAdmin();
                    $siteAdminInfo = $bllSiteAdmin->findByUid($admininfo['id'], now_site()['id']);
                    if ($siteAdminInfo['issuperadmin'] != 1) {


                        // 创建 SiteRole 类的实例
                        $bllSiteRole = new BllSiteRole();
                        // 根据站点管理员的角色 ID 列表查询对应的权限信息
                        $auths = $bllSiteRole->selAuthByIds(trim($siteAdminInfo['roleids'], ','));

                        // 若权限信息中不包含菜单信息或者菜单信息为空，抛出异常
                        if (!isset($auths['menus']) || !$auths['menus']) {
                            throw new Exception('没有权限');
                        }

                        // 从权限信息的菜单列表中提取菜单标识
                        $authmenuidents = array_column($auths['menus'], 'ident');

                        // 若当前站点标识不在权限菜单标识列表中，抛出异常
                        if (!in_array($nowmenu['ident'], $authmenuidents)) {
                            throw new Exception('没有权限');
                        }
                    }
                }

                request()->elementinfo = (array) $tokenArr['data'];
            } catch (Exception $ex) {
                throw new Exception($ex->getMessage());
            }
        }
        return $handler($request);
    }
}
